package main

import (
	"flag"
	espoirCom "gitee.com/jamon/espoir_go/common"
	"tankserver/lib"
	"tankserver/requesthandler"

	"gitee.com/jamon/espoir_go/frame"
	"gitee.com/jamon/espoir_go/global"
	"gitee.com/jamon/espoir_go/logger"
	"gitee.com/jamon/espoir_go/rpcserver"
	"gitee.com/jamon/espoir_go/websocketserver"
)

func initBeforeStart(path string) (err error) {
	// init config
	err = global.InitNodeData(path)
	if err != nil {
		logger.Error("initBeforeStart: ", logger.Kwargs{"err": err})
		return
	}

	// init inner msg override
	lib.OverrideInnerMsgID()

	// 注册requesthandler
	requesthandler.Start()
	return
}

func main() {
	var configPath = flag.String("config", "jsonfile/proxy_1.json", "config file path")
	var logLevel = flag.String("loglevel", "debug", "log level")
	var serviceName = flag.String("service_name", "proxy_1", "service name")
	flag.Parse()
	logger.InitConfig(*logLevel, *serviceName)
	defer func() {
		logger.Close()
	}()

	err := initBeforeStart(*configPath)
	if err != nil {
		return
	}

	if global.GetNodeData().Config.WebSocket != nil {
		go espoirCom.SafeRun(func() {
			logger.Info("websocket server init start")
			webMgr, err := websocketserver.NewManager()
			if err != nil {
				logger.Error("websocket server init failed: ", logger.Kwargs{"err": err})
				return
			}
			defer func() {
				webMgr.Close()
			}()
			err = webMgr.InitWebsocketServer()
			if err != nil {
				logger.Error("websocket server init failed: ", logger.Kwargs{"err": err})
				return
			}
			logger.Info("websocket server init success")
		})
	}

	logger.Info("rpc server init start")
	rpcMgr, err := rpcserver.NewManager()
	if err != nil {
		logger.Error("rpc server init failed: ", logger.Kwargs{"err": err})
		return
	}
	defer func() {
		rpcMgr.Close()
	}()
	err = rpcMgr.InitRpcServer()
	if err != nil {
		logger.Error("rpc server init failed: ", logger.Kwargs{"err": err})
		return
	}
	logger.Info("rpc server init success")

	if global.GetNodeData().Config.Frame.Enabled {
		go espoirCom.SafeRun(func() {
			logger.Info("frame server init start")
			frameMgr := frame.GetFrameManager()
			defer func() {
				frameMgr.Close()
			}()
			logger.Info("frame server init success")
			frameMgr.Run()
		})
	}

	rpcMgr.Run()
}
